<template>
  <section class="sp-searcion sp-bus">
    <!-- header -->
    <header class="sp-bus__header">
      <!-- search -->
      <div class="sp-bus__header-search">
         <el-select
    v-model="stop_name"
    filterable
    remote
    reserve-keyword
    placeholder="请输入车站关键词"
    :remote-method="remoteMethod"
    @change="changeName(stop_name)"
    :loading="loading">
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.name"
      :value="item.name">
    </el-option>
  </el-select>
          <!-- <el-input v-model="queryParams.stop_name" placeholder="请输入车站"></el-input> -->
        <el-select
          v-model="route"
          clearable
          multiple
          autocomplete
          filterable
          placeholder="请选择"
          style="width: 400px"
          @change="changeRoute">
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.route_name"
            :value="item.pure_name"
          />
        </el-select>
        <el-button @click="search">查询公交线路</el-button>
        <!-- <el-button @click="open = true">显示标记点</el-button> -->
      </div>
    </header>
    <!-- 地图 -->
    <div class="sp-bus__map">
      <el-amap
        ref="map"
        :plugin="plugin"
        defaultCursor="hand"
        :center="center"
        :zoom="zoom"
        vid="container"
        mapStyle="amap://styles/50471cf997eaa81d3140f305ae3a7fae"
      >
        <el-amap-marker
          v-for="(marker, index) in markers"
          :position="marker.position"
          :vid="index"
          :icon="marker.icon"
          :content="marker.content"
          :events="marker.events"
          :offset="marker.offset"
          :key="index"
        ></el-amap-marker>
        <el-amap-info-window
          v-if="window"
          :position="windows.position"
          :visible="windows.visible"
          :content="windows.content"
        ></el-amap-info-window>
      </el-amap>
        <el-card class="box-card" v-if="showDialog">
  <div slot="header" class="clearfix" >
    <img src="../../assets/WechatIMG1075.png" alt="" class="card_img"><span style="font-size:18px;margin-left: 10px;font-weight: 700;">{{route[0]}}路</span>
    <el-button style="float: right; padding: 3px 0" type="text" @click="showDialog=false">关闭</el-button>
  </div>
  <div class="dialog">
    <div class="dialog_top">
      <div ><span style="color:#f3c197">车辆计数:</span>{{car_num}}辆</div>
   <div>在售<span style="color:red">{{blank_num}}</span>辆媒体资源：</div>
    </div>
   <div class="carList">
     <div class="carItem" v-for="item in carList" :key="item.id" >
       <span>{{item.code}}</span>
       <span> <el-button size="mini" round type="success" @click="carItemAdd(item.id)">加入</el-button></span>
     </div>
     <!-- <div class="carItem">
       <span>粤A1234</span>
       <span> <el-button size="mini" round type="success">加入</el-button></span>
     </div>
     <div class="carItem">
       <span>粤A1234</span>
       <span> <el-button size="mini" round type="success">加入</el-button></span>
     </div>
     <div class="carItem">
       <span>粤A1234</span>
       <span> <el-button size="mini" round type="success">加入</el-button></span>
     </div>
     <div class="carItem">
       <span>粤A1234</span>
       <span> <el-button size="mini" round type="success">加入</el-button></span>
     </div>
     <div class="carItem">
       <span>粤A1234</span>
       <span> <el-button size="mini" round type="success">加入</el-button></span>
     </div> -->
   </div>
   <div class="station" >
     <div style="color:#f3c197">途径站点：</div>
      <div style="text-align: center;"><el-button type="warning" size="mini" round @click="showStops=!showStops">{{`${showStops?"折叠收起":"展开查看"}`}}</el-button></div>
      <div v-if="showStops"> <span v-for="(item,index) in via_stops" :key="index">{{`${item.name}${index!=via_stops.length-1?"→":""}`}}</span></div>
   </div>
  </div>
</el-card>
      <div>
      </div>
    </div>
  </section>
</template>

<script>
import { getBuslist, getRouteInfo, setFavorite, getRouteStop, getBusCar, addBusStop } from '@/api/bus'
import icon from '../../../static/images/busStopIcon.png'
export default {
  name: 'BusIndex',
  components: {},
  data () {
    return {
      showStops: false,
      center: [101.777795, 36.616621],
      zoom: 12,
      label: {
        // content: '微微一笑绝绝子',
        // offset: [10, 12]
      },
      route: [],
      list: [],
      plugin: [],
      // plugin: ["AMap.ToolBar"],
      markers: [],
      open: false,
      windows: {},
      window: '',
      via_stops: [],
      carList: [],
      car_num: null,
      blank_num: null,
      stop_name: '',
      options: [],
      loading: false,
      roteList: [], // 筛选后的线路
      showDialog: false
    }
  },
  created () {
    this.getBusData()
  },
  mounted () {
    // this.initMap();
  },
  methods: {
    changeName (name) {
      this.route = []
      this.getInitData(name)
      console.log(this.route)
      // this.roteList = this.list.filter((item) => {
      //   // 遍历list的数据
      //   return this.route[0].includes(item.pure_name) // 筛选出匹配数据
      //   // return item.id;
      // })
    },
    // 模糊搜索
    remoteMethod (query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.getRouteStop(query)
        }, 200)
      } else {
        this.options = []
      }
    },
    // 站点名字搜索
    async getRouteStop (query) {
      const params = {
        stop_name: query
      }
      const { data: { data } } = await getRouteStop(params)
      this.options = data
    },
    // 添加
    async addBusStop (datas) {
      const { data } = await addBusStop(datas)
    },
    // 获取线路信息
    async getInitData (val) {
      const params = {
        stop_name: val,
        page: 1,
        num: 10
      }
      const { routes } = await getBusCar(params)
      if (routes[0].pure_name === this.route[0]) {
        return
      } else {
        routes.map((item, index) => {
          this.route.push(routes[index].pure_name)
        })
      }

      console.log(this.route)
      this.roteList = this.list.filter((item) => {
        // 遍历list的数据
        return this.route[0].includes(item.pure_name) // 筛选出匹配数据
        // return item.id;
      })
    },
    async carItemAdd (id) {
      const { status } = await setFavorite({ bus_car_id: id })
      this.$notify[status ? 'success' : 'error']({
        title: status ? '成功' : '错误',
        message: status ? '添加车辆成功' : '添加车辆失败'
      })
      this.$parent.$children[0].$children[0].getLists()
      this.$parent.$children[0].$children[0].getCheckList()
      console.log(this.$parent)
      // this.$parent.$parent.$parent.$parent.$children[1].$children[0].$children[0].getCheckList()
    },
    changeRoute (val) {
      // console.log(this.list)
      console.log(val)
      if (val.length === 0) {
        this.showDialog = false
        this.$refs.map.$$getInstance().clearMap()
      }
      if (val.length === 1) {
        // console.log(val)
        this.roteList = this.list.filter((item) => {
        // 遍历list的数据
          return val.includes(item.pure_name) // 筛选出匹配数据
        // return item.id;
        })
        console.log(this.roteList)
      }
    },
    async getRouteInfo () {
      console.log(this.roteList[0].id)
      const param = {
        route_id: this.roteList[0].id
      }
      const { data } = await getRouteInfo(param)
      this.carList = data.cars
      this.car_num = data.car_num
      this.blank_num = data.route.blank_num
      console.log(data)
    },
    // initMap(map) {
    //   this.map = new AMap.Map("container", {
    //     center: [101.777795, 36.616621],
    //     label: {
    //       content: "",
    //       offset: [10, 12],
    //     },
    //     zoom: 14, // 缩放比例
    //   });
    //   console.log(this.map);
    // },
    search () {
      const that = this
      var linesearch = new AMap.LineSearch({
        pageIndex: 1, // 页码，默认值为1
        pageSize: 1, // 单页显示结果条数，默认值为20，最大值为50
        city: '西宁', // 限定查询城市，可以是城市名（中文/中文全拼）、城市编码，默认值为『全国』
        extensions: 'all' // 是否返回公交线路详细信息，默认值为『base』
      })
      // 执行公交路线关键字查询
      // this.route.forEach((item, index) => {

      this.$refs.map.$$getInstance().clearMap()
      // console.log(that.route)
      if (that.route.length === 0) {
        that.showDialog = false
      }
      this.markers = []
      // if (that.route.length == 1) {
      //   this.windows = {
      //     visible: true,
      //     position: [0, 0],
      //     content:
      //       '"<div>"+"站点名称："+item.stationName+"</div>"+"<div>"+"建站时间："+111+"</div>"+"<div>"+"地 址："+111+"</div>"+"<div>"+"温度："+"<span style="color: #66A0FF">"+111+"</span>"+"</div>"',
      //   };
      //   this.window = true;
      // }
      that.route.map((routeitem, routeIndex) => {
        // that.route.length == 1 &&
        //   (that.window = { position: [101.849219, 36.573628], visible: true });
        // console.log(that.window);
        linesearch.search(routeitem, function (status, result) {
          // 打印状态信息status和结果信息result
          if (status === 'complete' && result.info === 'OK') {
            // eslint-disable-next-line no-undef
            // console.log(
            //   result.lineInfo[0].via_stops.map((item) => {
            //     return { position: [item.R, item.Q], content: item.name };
            //   })
            // );
            that.windows.visible = false
            that.via_stops = result.lineInfo[0].via_stops
            // console.log(result.lineInfo[0].via_stops)
            // // this.addBusStop
            // result.lineInfo[0].via_stops.forEach((item, index) => {
            //   const param = {
            //     route_id: that.roteList[0].id,
            //     name: item.name,
            //     lng: item.location.R,
            //     lat: item.location.Q
            //   }
            //   that.addBusStop(param)
            //   // console.log(param)
            // })
            // let resobj = {}
            // paramList.forEach(item => {
            //   resobj = { ...resobj, ...item }
            // })
            // // that.addBusStop(param)
            // console.log(resobj)
            // console.log(paramList)
            // if (that.route.length == 1) {
            //   let { R, Q } = result.lineInfo[0].via_stops[0].location;
            //   let content = [
            //     '<div><img src=""" http:="" webapi.amap.com="" images="" autonavi.png="" "=""> ',
            //     '<div style=""padding:0px" 0px="" 4px;"=""><b>高德软件有限公司</b>',
            //     "电话 : 010-84107000   邮编 : 100102",
            //     "地址 : 北京市望京阜通东大街方恒国际中心A座16层</div></div>",
            //   ];
            //   let infoWindow = new AMap.InfoWindow({
            //     position: [R - 0.2, Q],
            //     content: content.join("<br>"), //传入 dom 对象，或者 html 字符串
            //   });
            //   // 打开信息窗体
            //   infoWindow.open(that.$refs.map.$$getInstance());
            //   // infoWindow2.open(that.$refs.map.$$getInstance());
            // }
            if (that.route.length == 1) {
              that.getRouteInfo()
              that.showDialog = true
              // console.log(result.lineInfo[0].via_stops)
              that.markers = [
                ...that.markers,
                ...result.lineInfo[0].via_stops.map((item) => {
                  return {
                    position: [item.location.lng, item.location.lat],
                    content: item.name,
                    offset: [-90, -90]
                    // icon,
                    // events:
                  }
                })
              ]
            }

            that.lineSearch_Callback(result)
          } else {
            alert(result)
          }
          // })
        })
      })
    },
    lineSearch_Callback (data) {
      var lineArr = data.lineInfo
      var lineNum = data.lineInfo.length
      // console.log(data.lineInfo.length)
      // eslint-disable-next-line eqeqeq
      console.log(lineArr)
      if (lineNum == 0) {
      } else {
        for (var i = 0; i < lineNum; i++) {
          var pathArr = lineArr[i].path
          var stops = lineArr[i].via_stops
          var startPot = stops[0].location
          var endPot = stops[stops.length - 1].location
          console.log(pathArr)
          // eslint-disable-next-line eqeqeq
          if (i == 0) {
            this.drawbusLine(startPot, endPot, pathArr)
          } // 作为示例，只绘制一条线路
        }
      }
    },
    drawbusLine (startPot, endPot, BusArr) {
      // console.log(this.map)
      // const that = this
      // 绘制起点，终点
      // eslint-disable-next-line no-new
      new AMap.Marker({
        map: this.$refs.map.$$getInstance(),
        position: startPot, // 基点位置
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
        zIndex: 10,
        anchor: 'bottom-center'
      })
      // eslint-disable-next-line no-new
      new AMap.Marker({
        map: this.$refs.map.$$getInstance(),
        position: endPot, // 基点位置
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
        zIndex: 10,
        anchor: 'bottom-center'
      })
      // 绘制乘车的路线
      var busPolyline = new AMap.Polyline({
        map: this.$refs.map.$$getInstance(),
        path: BusArr,
        strokeColor: '#09f', // 线颜色
        strokeOpacity: 0.8, // 线透明度
        isOutline: true,
        outlineColor: 'white',
        strokeWeight: 6 // 线宽
      })
      // 将 busPolyline 显示在地图中心并自动缩放地图到合适级别。
      // true表示需要动画过程，[60,200,60,60]表示上下左右避让像素
      this.$refs.map.$$getInstance().setFitView(busPolyline, [60, 200, 60, 60])
    },
    // 获取全部公交路线
    async getBusData () {
      const { data } = await getBuslist()
      this.list = data.map((item) => {
        item.checked = false
        return item
      })
    }
    // // 获取公交车类型
    // async getBusType() {
    //   const { data } = await getBusType();
    //   console.log("bustype", data);
    // },
    // // 设置某条线路选中
    // setBusChecked(index) {
    //   this.list[index].checked = !this.list[index].checked;
    // },
  }
}
</script>

<style lang="less" scoped>
@import url("./index.less");
.text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    padding: 0 24px;
    font-size: 14px;
    width: 240px;
     position: absolute;
    top: 120px;
    left: 120px;
    // width: 350px;
    min-height: 420px;
    z-index: 2;
    background: #fff;
    border-radius: 5px;
    /deep/ .el-card__body{
      padding: 0px;
    }
    /deep/ .el-card__header{
      border-bottom: 1px dashed #333;
    }
    .card_img{
      position: absolute;
      top: 18px;
      left: 25px;
    }
    .dialog_top{
      line-height: 30px;

      // margin-left: 20px;
    }
    .carList{
      background-color:#f5f6f6;
      padding-bottom: 20px;
      overflow-y: scroll;
      height: 186px;
      .carItem{
        display: flex;
        justify-content: space-around;
        margin-top: 12px;
      }
    }
    .station{
      line-height: 30px;

    }
  }
</style>
